package com.example.administrator.myapplication.find.anchor.fragment;


import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.myapplication.BR;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.callback.XmlyService;
import com.example.administrator.myapplication.databinding.FragmentAnchorBinding;
import com.example.administrator.myapplication.find.anchor.bean.anchorentity.AnchorEntity;
import com.example.administrator.myapplication.until.BaseApplication;
import com.example.administrator.myapplication.until.CommentRecyclerAdapter;

import java.util.ArrayList;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class AnchorFragment extends Fragment implements Callback<AnchorEntity>, PtrHandler {
    private FragmentAnchorBinding binding;
    private CommentRecyclerAdapter<Object> adapter;
    private XmlyService service;
    private int page = 1;
    private int isRefresh = -1;
    private boolean isLoading = false;

    public AnchorFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return DataBindingUtil.inflate(inflater, R.layout.fragment_anchor, container, false).getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = DataBindingUtil.getBinding(view);
        aboutRecycler();
        aboutNextPage();
        aboutRefresh();
    }

    private void aboutRefresh() {
        LinearLayout linearLayout = new LinearLayout(getContext());
        final ImageView imageView = new ImageView(getContext());
        final TextView textView = new TextView(getContext());
        imageView.setImageResource(R.mipmap.default_ptr_flip);
        textView.setText("下拉刷新");
        linearLayout.addView(textView);
        linearLayout.addView(imageView);
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        binding.ptr.setPtrHandler(this);
        binding.ptr.setHeaderView(linearLayout);
        binding.ptr.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                ViewCompat.setScaleY(imageView, 1);
                ViewCompat.setScaleX(imageView, 1);
                ViewCompat.setRotation(imageView, 0);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {

            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                textView.setText("正在刷新,请稍后...");
                ViewCompat.animate(imageView)
                        .rotation(180)
                        .setDuration(500)
                        .start();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {

            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                float percent = ptrIndicator.getCurrentPercent();
                percent = Math.min(percent, 1);
                ViewCompat.setScaleX(imageView, percent);
                ViewCompat.setScaleY(imageView, percent);
            }
        });
    }

    private void aboutNextPage() {
        binding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View item = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
                int position = recyclerView.getChildAdapterPosition(item);
                if (!isLoading && position > adapter.getItemCount() - 2) {
                    page = page + 1;
                    isLoading =true;
                    service.getAnchorEntity(page).enqueue(AnchorFragment.this);
                }
            }
        });
    }

    private void aboutRecycler() {
        adapter = new CommentRecyclerAdapter<>(getContext(), new ArrayList<>(), R.layout.anchor_item, BR.title1);
        binding.recycler.setAdapter(adapter);
        service = ((BaseApplication) getContext().getApplicationContext()).getService();
        service.getAnchorEntity(page).enqueue(this);

    }

    @Override
    public void onResponse(Call<AnchorEntity> call, Response<AnchorEntity> response) {
        if (isRefresh == -2) {
            adapter.clear();
        }
        adapter.addAll(response.body().getList());
        binding.ptr.refreshComplete();
        isRefresh=-1;
        isLoading =false;
    }

    @Override
    public void onFailure(Call<AnchorEntity> call, Throwable t) {
        t.getMessage();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        isRefresh = -2;
        page = 1;
        service.getAnchorEntity(page).enqueue(this);
    }
}
